package com.atguigu.daijia.driver.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    private final TencentCloudProperties tencentCloudProperties;

    @Override
    public CosUploadVo upload(MultipartFile file, String path) {

        try {
            COSClient cosClient = getCOSClient();
            //文件上传
            //元数据信息
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentLength(file.getSize());
            meta.setContentEncoding("UTF-8");
            meta.setContentType(file.getContentType());

            //向存储桶中保存文件
            String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //文件后缀名
            String uploadPath = "/driver/" + path + "/" + IdUtil.fastSimpleUUID() + fileType;
            // 01.jpg
            // /driver/auth/0o98754.jpg
            PutObjectRequest putObjectRequest;

            //1 bucket名称
            //2
            putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(),
                    uploadPath,
                    file.getInputStream(),
                    meta);

            putObjectRequest.setStorageClass(StorageClass.Standard);

            //上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            if (StrUtil.isBlank(putObjectResult.getETag())) {
                throw new GuiguException(ResultCodeEnum.FILE_UPDATE_ERROR);
            }
            cosClient.shutdown();
            //返回vo对象
            CosUploadVo cosUploadVo = new CosUploadVo();
            cosUploadVo.setUrl(uploadPath);
            String imageUrl = getImageUrl(uploadPath);
            cosUploadVo.setShowUrl(imageUrl);
            return cosUploadVo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取腾讯云cos实例
     *
     * @return
     */
    private COSClient getCOSClient() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        String secretId = tencentCloudProperties.getSecretId();
        String secretKey = tencentCloudProperties.getSecretKey();
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域
        Region region = new Region(tencentCloudProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }


    /**
     * 生成临时地址
     *
     * @param path
     * @return
     */
    @Override
    public String getImageUrl(String path) {
        if (StrUtil.isBlank(path)) {
            return StrUtil.EMPTY;
        }
        COSClient cosClient = getCOSClient();
        //GeneratePresignedUrlRequest
        GeneratePresignedUrlRequest request =
                new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(),
                        path, HttpMethodName.GET);
        //设置临时URL有效期为15分钟
        Date date = new DateTime().plusMinutes(15).toDate();
        request.setExpiration(date);
        //调用方法获取
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }
}
